package cn.net.asiacom.extrator.extra;

import cn.net.asiacom.entity.NewInvoice;
import cn.net.asiacom.utils.StrUtil;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static cn.net.asiacom.config.InvoiceRegexEnum.*;


/**
 * 处理电子发票识别类
 * 新版发票提取类（NewPdfInvoiceExtractor），
 * 新版全电发票识别类，通过加载和解析PDF文件，
 * 使用正则表达式匹配提取关键信息，包括发票号码、开票日期、金额、税额、合计、销售方名称
 */
public class NewPdfInvoiceExtractor {
    /**
     * 从指定的文件中提取发票信息。
     * @param file 要提取发票信息的文件。
     * @return 包含提取信息的 NewInvoice 对象。
     * @throws IOException 如果在提取过程中发生 I/O 错误。
     */
    public static NewInvoice extract(File file) throws IOException {
        NewInvoice invoice = new NewInvoice();
//        PDDocument doc = PDDocument.load(file);
        PDDocument doc = Loader.loadPDF(file);
        PDPage firstPage = doc.getPage(0);
 
        int pageWidth = Math.round(firstPage.getCropBox().getWidth());
 
        PDFTextStripper textStripper = new PDFTextStripper();
        textStripper.setSortByPosition(true);
 
        String fullText = textStripper.getText(doc);
 
        if (firstPage.getRotation() != 0) {
            pageWidth = Math.round(firstPage.getCropBox().getHeight());
        }
 
        String allText = StrUtil.replace(fullText);

        {
            Pattern pattern = Pattern.compile(REGULAR_A_NEW.getRegex());
            Pattern patternNumber = Pattern.compile(REGULAR_A_1.getRegex());
            Pattern patternDate = Pattern.compile(REGULAR_A_2.getRegex());

            Matcher matcher = pattern.matcher(allText);
            while (matcher.find()) {
                if (matcher.group("number") != null) {
                    invoice.setNumber(matcher.group("number"));
                } else if (matcher.group("date") != null) {
                    String rawDate = matcher.group("date");
                    try {
                        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
                        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");
 
                        Date parsedDate = inputDateFormat.parse(rawDate);
                        String formattedDate = outputDateFormat.format(parsedDate);
                        invoice.setDate(formattedDate);
                    } catch (ParseException e) {
                        System.out.println("无法解析日期：" + rawDate);
                    }
                } else if (matcher.group("name") != null) {
                    invoice.setSellerName(matcher.group("name"));
                }

                if (matcher.group("number") == null){
                    Matcher matcher2 = patternNumber.matcher(allText);
                    if (matcher2.find()) {
                        invoice.setNumber(matcher2.group("number"));
                    }
                }
                if (matcher.group("date") == null){
                    Matcher matcher3 = patternDate.matcher(allText);
                    if (matcher3.find()) {
                        String rawDate = matcher3.group("date");
                        try {
                            SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyyMM月dd日");
                            SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");

                            Date parsedDate = inputDateFormat.parse(rawDate);
                            String formattedDate = outputDateFormat.format(parsedDate);

                            invoice.setDate(formattedDate);
                        } catch (Exception e) {
                            System.out.println("无法解析日期：" + rawDate);
                        }
                    }
                }
            }

        }
        // 获取购买方信息
        {
            Pattern patternTitle = Pattern.compile(REGULAR_F_1.getRegex());
            Matcher matcher = patternTitle.matcher(allText);
            int i = 0;
            while (matcher.find()) {
                if (matcher.group("name") != null) {
                    invoice.setBuyerName(matcher.group("name").replaceAll("销名称",""));
                }
                // 获取购买方纳税人识别号/销售方纳税人识别号
                if (matcher.group("code")!= null && i == 0) {
                    i = 1;
                    invoice.setBuyerCode(matcher.group("code"));
                } else if (matcher.group("code")!= null && i == 1){
                    i = 0;
                    invoice.setSellerCode(matcher.group("code"));
                }
            }
        }
        {
//            PDFKeyWordPosition kwp = new PDFKeyWordPosition();
//            Map<String, List<Position>> positionListMap = kwp.getCoordinate(Arrays.asList("项目名称", "规格型号", "单位", "数量", "单价", "金额", "税率/征收率", "税额"), doc);
//            PDFTextStripperByArea stripper = new PDFTextStripperByArea();
//            stripper.setSortByPosition(true);
//            PDFTextStripperByArea detailStripper = new PDFTextStripperByArea();
//            detailStripper.setSortByPosition(true);

            Pattern patternItemDetails = Pattern.compile("税额\\s+(.*?)合计", Pattern.DOTALL);
            Matcher matcherItemDetails = patternItemDetails.matcher(allText);
            // 处理项目名称、规格型号、单位、数量、单价、金额、税率/征收率、税额
            if (matcherItemDetails.find()) {
                String itemDetailsLine = matcherItemDetails.group(1).trim();
                itemDetailsLine = itemDetailsLine.replace("\n"," ");
                String[] details = itemDetailsLine.split(" "); // 按空格分割

                if (details.length >= 8) { // 确保有足够的字段
                    //因部分名称过长，换行数据解析到最后进行拼接
                    String productName = details[0].trim(); // 项目名称
                    if (details.length >= 9){
                        productName = details[0].trim()+details[8].trim(); // 项目名称
                    }
                    String specification = details[1].trim(); // 规格型号
                    String unit = details[2].trim(); // 单位
                    Integer quantity = Integer.parseInt(details[3].trim()); // 数量
                    Double unitPrice = Double.parseDouble(details[4].trim()); // 单价
                    Double amount = Double.parseDouble(details[5].trim()); // 金额
                    String taxRate = details[6].trim(); // 税率/征收率
                    Double taxAmount = Double.parseDouble(details[7].trim()); // 税额

                    System.out.println("项目名称: " + productName);
                    System.out.println("规格型号: " + specification);
                    System.out.println("单位: " + unit);
                    System.out.println("数量: " + quantity);
                    System.out.println("单价: " + unitPrice);
                    System.out.println("金额: " + amount);
                    System.out.println("税率/征收率: " + taxRate);
                    System.out.println("税额: " + taxAmount);
                }
            }
        }

        // 获取合计金额和税额
        {
            Pattern pattern = Pattern.compile(REGULAR_B.getRegex());
            Matcher matcher = pattern.matcher(allText);
            if (matcher.find()) {
                try {
                    invoice.setAmount(new BigDecimal(matcher.group("amount")));
                } catch (Exception e) {
                    // 不处理
                }
                try {
                    invoice.setTaxAmount(new BigDecimal(matcher.group("taxAmount")));
                } catch (Exception e) {
                    invoice.setTaxAmount(new BigDecimal(0));
                }
            }
            // 备用1：获取合计金额和税额
            if (null == invoice.getAmount()) {
                pattern = Pattern.compile(REGULAR_B_1.getRegex());
                matcher = pattern.matcher(fullText);
                if (matcher.find()) {
                    try {
                        invoice.setAmount(new BigDecimal(matcher.group("amount")));
                    } catch (Exception e) {
                        // TODO 不处理
                    }
                    try {
                        invoice.setTaxAmount(new BigDecimal(matcher.group("taxAmount")));
                    } catch (Exception e) {
                        invoice.setTaxAmount(new BigDecimal(0));
                    }
                }
            }
            // 备用2：获取合计金额和税额
            if (null == invoice.getAmount()) {
                pattern = Pattern.compile(REGULAR_B_2.getRegex());
                matcher = pattern.matcher(fullText);
                if (matcher.find()) {
                    try {
                        invoice.setAmount(new BigDecimal(matcher.group("amount")));
                    } catch (Exception e) {
                        invoice.setAmount(new BigDecimal(0));
                    }
                    try {
                        invoice.setTaxAmount(new BigDecimal(matcher.group("taxAmount")));
                    } catch (Exception e) {
                        invoice.setTaxAmount(new BigDecimal(0));
                    }
                }
            }
        }
        invoice.setTotalAmount(invoice.getAmount().add(invoice.getTaxAmount()));
        // 加税合计大写
        {
            Pattern pattern = Pattern.compile(REGULAR_C.getRegex());
            Matcher matcher = pattern.matcher(allText);
            if (matcher.find()) {
                invoice.setTotalAmountString(matcher.group("amountString"));
                try {
                    if (invoice.getTotalAmount() == null) {
                        invoice.setTotalAmount(new BigDecimal(matcher.group("amount")));
                    }
                } catch (Exception e) {
                    invoice.setTotalAmount(new BigDecimal(0));
                }
            }
        }
        // 收款人、复核、开票人
        {
            Pattern pattern = Pattern.compile(REGULAR_D.getRegex());
            Matcher matcher = pattern.matcher(allText);
            if (matcher.find()) {
                invoice.setPayee(matcher.group("payee"));
                invoice.setReviewer(matcher.group("reviewer"));
                invoice.setDrawer(matcher.group("drawer"));
            }
            pattern = Pattern.compile(REGULAR_D_1.getRegex());
            matcher = pattern.matcher(allText);
            if (matcher.find()) {
                invoice.setDrawer(matcher.group("drawer"));
            }
        }
        // 发票标题 和 发票类型
        {
            Pattern type00Pattern = Pattern.compile(REGULAR_E.getRegex());
            Matcher m00 = type00Pattern.matcher(allText);
            if (m00.find()) {
                invoice.setTitle(m00.group("p") + "通发票)");
                if (null == invoice.getType()) {
                    invoice.setType("普通发票");
                }
            } else {
                Pattern type01Pattern = Pattern.compile(REGULAR_E_1.getRegex());
                Matcher m01 = type01Pattern.matcher(allText);
                if (m01.find()) {
                    invoice.setTitle(m01.group("p") + "用发票)");
                    if (null == invoice.getType()) {
                        invoice.setType("专用发票");
                    }
                }
            }
        }
        return invoice;
 
    }

}